<?php

define('TEMPLATE_WEUI', '../addons/dayu_form_plugin_radio/template/weui/');
defined('IN_IA') or exit('Access Denied');
class dayu_form_plugin_radioModuleSite extends WeModuleSite
{
	private $table_category = 'dayu_form_plugin_radio_category';
	private $table_radio = 'dayu_form_plugin_radio';
	public function doWebCategory()
	{
		global $_GPC, $_W;
		require 'fans.web.php';
		$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
		if ($operation == 'display') {
			$pindex = max(1, intval($_GPC['page']));
			$psize = 15;
			$category = pdo_fetchall("select * from " . tablename($this->table_category) . " where weid = :weid ORDER BY id DESC", array(':weid' => $weid));
			$total = pdo_fetchcolumn("SELECT count(id) FROM " . tablename($this->table_category) . " where weid = :weid ORDER BY id DESC", array(':weid' => $weid));
			$pager = pagination($total, $pindex, $psize);
			foreach ($category as $key => $val) {
				$category[$key]['n'] = $this->get_kami_total($val['id'], 1);
				$category[$key]['o'] = $this->get_kami_total($val['id'], 2);
				$category[$key]['a'] = $this->get_kami_total($val['id'], 5);
			}
			include $this->template('category');
		} elseif ($operation == 'post') {
			$id = intval($_GPC['id']);
			if (!empty($id)) {
				$cate = pdo_get($this->table_category, array('weid' => $weid, 'id' => $id), array());
			}
			if (checksubmit('submit')) {
				if (empty($_GPC['title'])) {
					message('抱歉，请输入分类名称！');
				}
				$data = array('weid' => $weid, 'title' => $_GPC['title'], 'status' => $_GPC['status']);
				if (!empty($id)) {
					pdo_update($this->table_category, $data, array('id' => $id));
				} else {
					pdo_insert($this->table_category, $data);
					$id = pdo_insertid();
				}
				message('更新分类成功！', $this->createWebUrl('Radio', array('op' => 'display')), 'success');
			}
			include $this->template('category');
		} elseif ($operation == 'delete') {
			$id = intval($_GPC['id']);
			$category = pdo_fetch("SELECT * FROM " . tablename($this->table_category) . " WHERE id = '$id'");
			if (empty($category)) {
				message('抱歉，分类不存在或是已经被删除！', $this->createWebUrl('Radio', array('op' => 'display')), 'error');
			}
			pdo_delete($this->table_category, array('id' => $id));
			message('分类删除成功！', $this->createWebUrl('Radio', array('op' => 'display')), 'success');
		}
	}
	public function get_kami_total($cid, $type)
	{
		global $_GPC, $_W;
		if ($type == '1') {
			return pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename($this->table_radio) . " WHERE weid = :weid AND cid = :cid AND status = 0", array(":weid" => $_W['uniacid'], ":cid" => $cid));
		} elseif ($type == '2') {
			return pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename($this->table_radio) . " WHERE weid = :weid AND cid = :cid AND status = 1", array(":weid" => $_W['uniacid'], ":cid" => $cid));
		}
	}
	public function doWebRadio()
	{
		global $_GPC, $_W;
		require 'fans.web.php';
		$id = $_GPC['id'];
		$cid = $_GPC['cid'];
		$status = $_GPC['status'];
		$op = $operation = $_GPC['op'] ? $_GPC['op'] : 'display';
		if (empty($cid)) {
			message('选项分类不能空', referer(), 'error');
		}
		if ($op == 'display') {
			$pindex = max(1, intval($_GPC['page']));
			$psize = 15;
			$where .= 'weid=:weid and cid=:cid';
			$params = array();
			$params[':weid'] = $weid;
			$params[':cid'] = $cid;
			if (!empty($_GPC['title'])) {
				$where .= ' and title like :title';
				$params[':title'] = "%{$_GPC['title']}%";
			}
			if ($status != '') {
				$where .= ' and status=' . $status;
			}
			$sql = 'SELECT * FROM ' . tablename($this->table_radio) . " WHERE $where ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize;
			$list = pdo_fetchall($sql, $params);
			$total = pdo_fetchcolumn("SELECT count(id) FROM " . tablename($this->table_radio) . " WHERE $where", $params);
			$pager = pagination($total, $pindex, $psize);
			foreach ($list as &$val) {
				$val['fans'] = mc_fansinfo($val['openid'], $acid, $weid);
				$val['model'] = $val['addons'] == 'dayu_form' ? '表单链接' : '预约链接';
			}
		} elseif ($op == 'detail') {
			$item = pdo_get($this->table_radio, array('weid' => $weid, 'id' => $id), array());
			$fan = pdo_get('mc_mapping_fans', array('uniacid' => $weid, 'openid' => $item['openid']), array());
			$piclist1 = unserialize($item['album']);
			$piclist = array();
			if (is_array($piclist1)) {
				foreach ($piclist1 as $p) {
					$piclist[] = is_array($p) ? $p['attachment'] : $p;
				}
			}
			if (checksubmit('submit')) {
				$data = array('title' => $_GPC['title'], 'thumb' => $_GPC['thumb'], 'status' => $_GPC['status'], 'createtime' => TIMESTAMP);
				if (is_array($_GPC['album'])) {
					$data['album'] = serialize($_GPC['album']);
				}
				pdo_update($this->table_radio, $data, array('weid' => $weid, 'id' => $id));
				message('选项保存成功！', $this->createWebUrl('Radio', array('cid' => $cid)), 'success');
			}
		} elseif ($op == 'post') {
			$fan = pdo_get('mc_mapping_fans', array('uniacid' => $weid, 'openid' => $item['openid']), array());
			if (checksubmit('submit')) {
				$data = array('weid' => $weid, 'cid' => $cid, 'title' => $_GPC['title'], 'thumb' => $_GPC['thumb'], 'status' => $_GPC['status'], 'createtime' => TIMESTAMP);
				if (is_array($_GPC['album'])) {
					$data['album'] = serialize($_GPC['album']);
				}
				pdo_insert($this->table_radio, $data);
				message('选项保存成功！', $this->createWebUrl('Radio', array('cid' => $cid)), 'success');
			}
		} elseif ($op == 'delete') {
			$id = intval($_GPC['id']);
			$item = pdo_get($this->table_radio, array('weid' => $weid, 'id' => $id), array());
			if (empty($item)) {
				message('抱歉，选项不存在或是已经被删除！', $this->createWebUrl('Radio', array('cid' => $cid)), 'error');
			}
			pdo_delete($this->table_radio, array('weid' => $weid, 'id' => $id));
			message('删除成功', $this->createWebUrl('Radio', array('cid' => $cid)), 'success');
		}
		if ($op == 'del') {
			$_W['page']['title'] = '删除选项';
			if (checksubmit('submit')) {
				$recycle = $_GPC['recycle'];
				if (!empty($_GPC['kid'])) {
					$delete_uids = array();
					foreach ($_GPC['kid'] as $kid) {
						$kid = intval($kid);
						if (!empty($kid)) {
							$delete_uids[] = intval($kid);
						}
					}
					if (!empty($delete_uids)) {
						$data = array('recycle' => 1);
						$tables = array($this->table_radio);
						foreach ($tables as $key => $value) {
							pdo_update($value, $data, array('weid' => $weid, 'id' => $delete_uids));
							if (empty($recycle)) {
								pdo_update($value, $data, array('weid' => $weid, 'id' => $delete_uids));
							} else {
								pdo_delete($value, array('weid' => $weid, 'id' => $delete_uids));
							}
						}
						message($recycle_msg, referer(), 'success');
					}
				}
				message('请选择要删除的选项！', referer(), 'error');
			}
		}
		include $this->template('radio');
	}
	public function doMobileget()
	{
		global $_GPC, $_W;
		require 'fans.mobile.php';
		$id = intval($_GPC['id']);
		$item = pdo_get($this->table_radio, array('weid' => $weid, 'id' => $id), array());
		$item['album'] = unserialize($item['album']);
		if (is_array($item['album'])) {
			foreach ($item['album'] as $p) {
				$piclist .= is_array($p) ? "" : '<div class="swiper-slide"><img src=' . tomedia($p) . ' data-src=' . tomedia($p) . '></div>';
				$dot .= is_array($p) ? "" : "<span></span>";
			}
		}
		$result['status'] = 1;
		$result['piclist'] = $piclist;
		$result['dot'] = $dot;
		$result['title'] = $item['title'];
		message($result, '', 'ajax');
	}
	public function doWebAjaxSet()
	{
		global $_GPC, $_W;
		require 'fans.web.php';
		$id = intval($_GPC['id']);
		$type = $_GPC['type'];
		$data = intval($_GPC['data']);
		$table = $_GPC['table'];
		if ($table == 'member') {
		}
		if (in_array($type, array('status'))) {
			$data = $data == 1 ? '0' : '1';
			pdo_update($table, array($type => $data), array("id" => $id, "weid" => $weid));
			die(json_encode(array("result" => 1, "data" => $data)));
		}
		die(json_encode(array("result" => 0)));
	}
	public function send_template_message($data)
	{
		global $_W, $_GPC;
		$atype = 'weixin';
		$account_code = "account_weixin_code";
		load()->classs('weixin.account');
		$access_token = WeAccount::token();
		$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
		$response = ihttp_request($url, $data);
		if (is_error($response)) {
			return error(-1, "访问公众平台接口失败, 错误: {$response['message']}");
		}
		$result = @json_decode($response['content'], true);
		if (empty($result)) {
			return error(-1, "接口调用失败, 元数据: {$response['meta']}");
		} elseif (!empty($result['errcode'])) {
			return error(-1, "访问微信接口错误, 错误代码: {$result['errcode']}, 错误信息: {$result['errmsg']}");
		}
		return true;
	}
	public function AjaxMessage($msg, $status = 0)
	{
		$result = array('message' => $msg, 'status' => $status);
		echo json_encode($result);
		exit;
	}
	public function get_userinfo($weid, $openid)
	{
		load()->model('mc');
		return mc_fetch($openid);
	}
	public function get_info($uid)
	{
		global $_W;
		return pdo_fetch("SELECT * FROM " . tablename('mc_members') . " WHERE uniacid = :uniacid AND uid = :uid", array(':uniacid' => $_W['uniacid'], ':uid' => $uid));
	}
	public function doMobileFansUs()
	{
		global $_W, $_GPC;
		$qrcodesrc = tomedia('qrcode_' . $_W['acid'] . '.jpg');
		include $this->template('fans_us');
	}
	public function getFollow()
	{
		global $_GPC, $_W;
		$p = pdo_fetch("SELECT follow FROM " . tablename('mc_mapping_fans') . " WHERE uniacid = :weid AND openid = :openid LIMIT 1", array(":weid" => $_W['uniacid'], ":openid" => $_W['openid']));
		if (intval($p['follow']) == 0) {
			header('Location: ' . $this->createMobileUrl('FansUs'), true, 301);
		} else {
			return true;
		}
	}
	public function showMessage($msg, $redirect = '', $type = '')
	{
		global $_W;
		if ($redirect == 'refresh') {
			$redirect = $_W['script_name'] . '?' . $_SERVER['QUERY_STRING'];
		} elseif (!empty($redirect) && !strexists($redirect, 'http://')) {
			$urls = parse_url($redirect);
			$redirect = $_W['siteroot'] . 'app/index.php?' . $urls['query'];
		}
		if ($redirect == '') {
			$type = in_array($type, array('success', 'error', 'info', 'warning', 'ajax', 'sql')) ? $type : 'info';
		} else {
			$type = in_array($type, array('success', 'error', 'info', 'warning', 'ajax', 'sql')) ? $type : 'success';
		}
		if ($_W['isajax'] || $type == 'ajax') {
			$vars = array();
			$vars['message'] = $msg;
			$vars['redirect'] = $redirect;
			$vars['type'] = $type;
			exit(json_encode($vars));
		}
		if (empty($msg) && !empty($redirect)) {
			header('location: ' . $redirect);
		}
		$label = $type;
		if ($type == 'error') {
			$label = 'danger';
			$info = '出错了，原因：';
		}
		if ($type == 'ajax' || $type == 'sql') {
			$label = 'warning';
			$info = '访问受限，原因：';
		}
		if ($type == 'info') {
			$label = 'info';
			$info = '提示';
		}
		if ($type == 'success') {
			$info = '操作成功';
		}
		if (defined('IN_API')) {
			exit($msg);
		}
		include $this->template('messages', TEMPLATE_INCLUDEPATH);
		exit;
	}
}